<route lang="json5" type="page">
  {
    needLogin: true,
    style: {
      navigationBarTitleText: '消息中心',
      enablePullDownRefresh: true,
    },
  }
</route>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'

// 消息项的类型定义
interface Message {
  icon: string
  title: string
  content: string
  date: string
}

type LoadMoreStatus = 'more' | 'loading' | 'noMore'

const messageList = ref<Message[]>([])
const loadingStatus = ref<LoadMoreStatus>('more') // 'more', 'loading', 'noMore'
const page = ref(1)
const pageSize = 10

const wdState = computed<'loading' | 'finished' | null>(() => {
  if (loadingStatus.value === 'loading') {
    return 'loading'
  }
  if (loadingStatus.value === 'noMore') {
    return messageList.value.length > 0 ? 'finished' : null
  }
  return null
})

// 模拟的图标，可以根据实际情况修改
const icons = [
  'icon-wrench',
  'icon-app',
  'icon-water-drop',
  'icon-flash',
  'icon-dollar',
]
let iconIndex = 0

// 模拟获取消息数据
function createMockMessage(id: number): Message {
  const messageType = ['物业通知', 'app通知']
  const contentTemplates = [
    '将在xxx施工停电',
    '将在xxx进行软件升级',
    '501水表表内余额低于预警额度，请尽快充值操作',
    '501电表表内余额低于预警额度，请尽快充值操作',
    `您在 ${new Date().toLocaleTimeString()} 的充值100的充值凭证, 如有需要, 点击下载`,
  ]
  const type = messageType[id % messageType.length]
  const content = contentTemplates[id % contentTemplates.length]
  const date = new Date(Date.now() - id * 1000 * 60 * 60 * 24).toISOString().split('T')[0].replace(/-/g, '.')

  const icon = icons[iconIndex % icons.length]
  iconIndex++

  return {
    icon,
    title: type,
    content: `${id}: ${content}`,
    date,
  }
}

async function fetchMessages(pageNum: number, num: number) {
  return new Promise<Message[]>((resolve) => {
    setTimeout(() => {
      const data: Message[] = []
      const startId = (pageNum - 1) * num
      for (let i = 0; i < num; i++) {
        data.push(createMockMessage(startId + i))
      }
      resolve(data)
    }, 500)
  })
}

async function loadMessages(reload = false) {
  if (reload) {
    page.value = 1
    iconIndex = 0
  }

  if (loadingStatus.value === 'noMore' && !reload)
    return

  loadingStatus.value = 'loading'

  try {
    const res = await fetchMessages(page.value, pageSize)
    if (reload) {
      messageList.value = []
    }

    if (res.length > 0) {
      messageList.value.push(...res)
      page.value++
      loadingStatus.value = 'more'
    }
    else {
      loadingStatus.value = 'noMore'
    }
  }
  catch (error) {
    console.error('Failed to fetch messages:', error)
    loadingStatus.value = 'more'
  }
}

// onMounted
loadMessages(true)

// 下拉刷新
onPullDownRefresh(async () => {
  console.log('下拉刷新')
  await loadMessages(true)
  uni.stopPullDownRefresh()
})

// 上拉加载
onReachBottom(() => {
  loadMessages()
})

function clearMessages() {
  if (messageList.value.length === 0) {
    uni.showToast({
      title: '已经是空的啦',
      icon: 'none',
    })
    return
  }

  uni.showModal({
    title: '提示',
    content: '确定要清空所有消息吗？',
    success: (res) => {
      if (res.confirm) {
        messageList.value = []
        loadingStatus.value = 'noMore'
        page.value = 1
        iconIndex = 0
        uni.showToast({
          title: '已清空',
          icon: 'success',
        })
      }
    },
  })
}
</script>

<template>
  <view class="message-list-page">
    <view v-if="messageList.length === 0 && loadingStatus !== 'loading'" class="status-container">
      <wd-status-tip image="search" tip="暂无消息" />
    </view>
    <template v-else>
      <view class="message-list-page-header mb-3 flex justify-end">
        <wd-button type="error" size="small" @click="clearMessages">
          清空消息
        </wd-button>
      </view>
      <view v-for="(item, index) in messageList" :key="index" class="message-item">
        <view class="icon-wrapper">
          <text class="iconfont" :class="[item.icon]" />
        </view>
        <view class="content-wrapper">
          <view class="title-bar">
            <text class="title">
              {{ item.title }}
            </text>
            <text class="date">
              {{ item.date }}
            </text>
          </view>
          <text class="content">
            {{ item.content }}
          </text>
        </view>
      </view>
    </template>
    <wd-loadmore v-if="wdState" :state="wdState" />
  </view>
</template>

<style lang="scss" scoped>
// 引入iconfont
@import '@/style/iconfont.css';

.message-list-page {
  padding: 12px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .icon-wrapper {
    margin-right: 12px;
    .iconfont {
      font-size: 24px;
      color: #333;
    }
    // 为不同的图标设置颜色
    .icon-wrench {
      color: #f29b40;
    }
    .icon-app {
      color: #4a90e2;
    }
    .icon-water-drop {
      color: #50e3c2;
    }
    .icon-flash {
      color: #f5a623;
    }
    .icon-dollar {
      color: #7ed321;
    }
  }

  .content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .title-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    margin-bottom: 8px;
  }

  .title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }

  .date {
    font-size: 12px;
    color: #999;
  }

  .content {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
  }
}

.status-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 50px;
  color: #999;
  font-size: 14px;
}
</style>
